package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.ws.soap.Addressing;
import java.util.List;

@Service
@Transactional
public class DishServiceimpl extends ServiceImpl<DishMapper,Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Override
    public void savawithFlavor(DishDto dishDto) {
        //dishId在dishservice保存时自动生成了 并且保存在了dishDto里
        this.save(dishDto);
        //将dishDto里的dishId取出来
        Long id = dishDto.getId();
        //将dishDto的DishFlavor里加上dishId
        List<DishFlavor> flavors = dishDto.getFlavors();
        //遍历flavors 将DishId设置flavor里
        flavors.forEach((flavor)->{
            flavor.setDishId(id);
        });
        //将口味保存到dishFlavor数据表里
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public void deleteByIds(Long[] ids) {

    }

    @Override
    public DishDto getWithFlavor(Long id) {
        DishDto dishDto=new DishDto();
        Dish dish = this.getById(id);
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }
}
